/**
 * 	http://open.weibo.com/development
 *
 * 	sdk api测试
 * 	http://flashsdk.sinaapp.com/WeiboFlashPlatformManual.html
 * 
 * 	as doc
 *  http://flashsdk.sinaapp.com/doc/index.html
 *
 * 	OAuth:
 * 	http://open.weibo.com/wiki/index.php/Oauth#.E7.94.A8.E6.88.B7.E8.AE.A4.E8.AF.81
 *
 * 	Flash AIR应用，使用HTMLLoader调用官方授权登录，避开PIN和XAuth:
 * 	http://forum.open.weibo.com/read.php?tid=7080
 *
 * 	OAuth
 * 	http://open.weibo.com/wiki/index.php/Oauth
 *
 * 1399509239
 * 69813a7ed7e4442fd6781dd14c60ff88
 *	
 * 	开发微博Flash应用详解
 * 	http://forum.open.weibo.com/read.php?tid=10025
 * 
 * 	OAUTH协议简介
 * 	http://blog.csdn.net/hereweare2009/article/details/3968582
 * 
 * 
 * 	-------------------------------------------------------------------------------------
 * 
 * 
 * 
 * 
 * 	App Key是应用的唯一标识，开放平台通过App Key来鉴别应用的身份。 
 * 	AppSecret是给应用分配的密钥，开发者需要妥善保存这个密钥，这个密钥用来保证应用来源的的可靠性，防止被伪造。
 * 
 * 
 * 
 * 	-------------------------------------------------------------------------------------
 * 
 * 	认证登陆全过程：(问sina同意 -> 问用户同意 -> 都同意了向sina要令牌)
 * 	1.请求签名：生成base string(包括要发送的key和secret)
 *
 *  2.获取request token（得到oauth_token和oauth_token_secret）
 *	目的：第一，告诉新浪微博你将要做什么，第二，告诉新浪微博你在callback里要做什么 
 * 
 * 	3.用户认证(发送oauth_token)，1)已认证（已经登陆，但air没这情况） 2)未认证（HTMLLoader加载登陆框）
 * 	用户确定是否对此应用进行授权。
 * 
 *  4.获取access token（登陆过且授权才能得到）
 * 	向"/oauth/access_token"发送access token，为了得到用户信息
 * 
 *  5.获取用户信息
 * 	
 * 	
 *
 */

import com.adobe.crypto.HMAC;
import com.adobe.crypto.SHA1;
import com.dynamicflash.util.Base64;
import com.sina.microblog.MicroBlog;
import com.sina.microblog.data.MicroBlogUser;
import com.sina.microblog.events.MicroBlogErrorEvent;
import com.sina.microblog.events.MicroBlogEvent;
import com.sina.microblog.utils.GUID;
import com.sina.microblog.utils.StringEncoders;
import com.yf.weiboair.container.Container;
import com.yf.weiboair.statics.Statics;

import components.MainList;
import components.Retweeted;
import components.UserProfile;
import components.Write;
import components.Play;

import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.SecurityErrorEvent;
import flash.html.HTMLLoader;
import flash.net.LocalConnection;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;

import flashx.textLayout.conversion.TextConverter;

import mx.core.UIComponent;
import mx.controls.Alert;
import spark.components.Group;
import spark.components.Label;
import spark.components.VGroup;


private var _mb:MicroBlog;
private var _consumerKey:String="1399509239";//key和secret：向新浪微博开放平台表明自己身份的合法性
private var _consumerSecret:String="69813a7ed7e4442fd6781dd14c60ff88";
private var _accessTokenKey:String=""; //oauth_token
private var _accessTokenSecret:String=""; //oauth_token_secret
private var _pin:String="";
private var _source:String="0000000000";


private var oauthLoader:URLLoader;
private var _html:HTMLLoader;
private var mainContainer:UIComponent=new UIComponent();
private var profileXML:XML; //个人信息
private var userProfile:UserProfile;
private var rtCounterArr:Array = new Array();//引用的原微博的id，请求原微博转发评论用
private var retweetedArr:Array = new Array();//引用的原微博显示组件
private var rtCounterNum:int = 0;//0原，1引用
private var writeComponent:Write;//写微博的小框



public function init():void
{
	this.showStatusBar=false;
	
	_mb=new MicroBlog();
	_mb.source=_consumerKey;
	_mb.consumerKey=_consumerKey;
	_mb.consumerSecret=_consumerSecret;
	_mb.isTrustDomain=true;
	_mb.addEventListener(MicroBlogEvent.VERIFY_CREDENTIALS_RESULT, onVerifyCredentialResult);
	_mb.addEventListener(MicroBlogErrorEvent.VERIFY_CREDENTIALS_ERROR, verifyCredentialsError);

	if (null == oauthLoader)
	{
		oauthLoader=new URLLoader();
		oauthLoader.addEventListener(Event.COMPLETE, oauthLoader_onComplete, false, 0, true);
		oauthLoader.addEventListener(IOErrorEvent.IO_ERROR, oauthLoader_onError, false, 0, true);
		oauthLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, oauthLoader_onSecurityError, false, 0, true);
	}

	var req:URLRequest=new URLRequest(Statics.OAUTH_REQUEST_TOKEN_REQUEST_URL);
	req.method=URLRequestMethod.POST;

	var params:URLVariables=new URLVariables;
	var now:Date=new Date();
	params["oauth_consumer_key"]=_consumerKey;
	params["oauth_signature_method"]="HMAC-SHA1";
	params["oauth_timestamp"]=now.time.toString().substr(0, 10);
	params["oauth_nonce"]=GUID.createGUID();//GUID是一个通过特定算法产生的二进制长度为128位的数字标识符，用于指示产品的唯一性。
	params["oauth_version"]="1.0";
	params["oauth_callback"]="http://api.t.sina.com.cn/flash/callback.htm";

	var retParams:Array=[];
	for (var param:String in params)
	{
		if (params[param] != null)
			retParams.push(param + "=" + StringEncoders.urlEncodeUtf8String(params[param].toString()));
	}
	retParams.sort();
	var paramsStr:String=retParams.join("&");

	var msgStr:String=StringEncoders.urlEncodeUtf8String(URLRequestMethod.POST.toUpperCase()) + "&";
	msgStr+=StringEncoders.urlEncodeUtf8String(Statics.OAUTH_REQUEST_TOKEN_REQUEST_URL);
	msgStr+="&";
	msgStr+=StringEncoders.urlEncodeUtf8String(paramsStr);

	var secrectStr:String=_consumerSecret + "&";
	var sig:String=Base64.encode(HMAC.hash(secrectStr, msgStr, SHA1));
	params["oauth_signature"]=sig;

	req.data=params;
	oauthLoader.load(req);//请求用户未授权的request_token；oauthLoader_onComplete
}


/**
 *	成功获得oauth_token和oauth_token_secret
 * 	加载到登陆页一次，登陆成功又一次
 * @param event
 *
 */
private function oauthLoader_onComplete(event:Event):void
{
	var needRequestAuthorize:Boolean=_accessTokenKey.length == 0;
	var result:String=oauthLoader.data as String;

	//trace("oauthLoader_onComplete : "+result);
	//oauthLoader_onComplete : oauth_token=4acfe49c6e92002efcf36f652229f37c&oauth_token_secret=4cbe1ba42a43675e60e77811bdd6b9f8

	if (result.length > 0)
	{
		var urlVar:URLVariables=new URLVariables(oauthLoader.data);
		_accessTokenKey=urlVar.oauth_token;
		_accessTokenSecret=urlVar.oauth_token_secret;

		if (needRequestAuthorize)
		{
			//未登陆
			requestAuthorize();
			needRequestAuthorize=false;
		}
		else
		{
			//已登陆
			mainContainer.removeChild(_html);
			_mb.accessTokenKey=_accessTokenKey; //accessTokenKey : 是用于OAuth认证的访问资源的token，由用户授权
			_mb.accessTokenSecrect=_accessTokenSecret;
			_mb.verifyCredentials(); //用户认证  onVerifyCredentialResult
		}
	}
	else
	{
		trace("请求oauth_token和oauth_token_secret失败");
	}

}

private function oauthLoader_onError(event:IOErrorEvent):void
{
	trace("oauthLoader_onError");
}

private function oauthLoader_onSecurityError(event:SecurityErrorEvent):void
{
	trace("oauthLoader_onSecurityError");
}




/**
 *	请求授权，登陆
 *
 */
private function requestAuthorize():void
{
	var url:String=Statics.OAUTH_AUTHORIZE_REQUEST_URL;//http://api.t.sina.com.cn/oauth/authorize
	url+="?oauth_token=" + StringEncoders.urlEncodeUtf8String(_accessTokenKey);
	url+="&oauth_callback=http://api.t.sina.com.cn/flash/callback.htm";//变向将参数带到了onLocationChange中

	_html=new HTMLLoader();
	var urlReq:URLRequest=new URLRequest(url);
	_html.addEventListener(Event.LOCATION_CHANGE, onLocationChange);
	_html.width=650;
	_html.height=400;
	_html.load(urlReq);//加载授权的页面，onLocationChange
	_html.x=0;
	_html.y=0;

	mainContainer.addChild(_html);
	this.addElement(mainContainer);
}

/**
 *	返回授权页
 * 	登陆页一次，登陆页登陆成功又一次
 * @param e
 *
 */
private function onLocationChange(e:Event):void
{
	var lc:String=_html.location;
	var arr:Array=String(lc.split("?")[1]).split("&");
	var oauth_token:String="";
	var oauth_verifier:String="";
	for (var i:int=0; i < arr.length; i++)
	{
		var str:String=arr[i];
		/*
		trace(str);
		oauth_token=a44e14c6fd163090794cadbb2489499c
		oauth_callback=http://api.t.sina.com.cn/flash/callback.htm
		*/
		if (str.indexOf("oauth_token=") >= 0)
			oauth_token=str.split("=")[1];
		if (str.indexOf("oauth_verifier=") >= 0)
			oauth_verifier=str.split("=")[1];
	}
	//trace("oauth_verifier="+oauth_verifier);//登陆前为空，因为无oauth_verifier返回
	if (oauth_verifier != "")
	{
		
		//登陆成功后才可执行到此
		
		_pin=oauth_verifier;//pin其实就是oauth_verifier

		var req:URLRequest=new URLRequest(Statics.OAUTH_ACCESS_TOKEN_REQUEST_URL);
		req.method=URLRequestMethod.POST;

		var params:URLVariables=new URLVariables;
		var now:Date=new Date();
		params["oauth_consumer_key"]=_consumerKey;
		if (_accessTokenKey.length > 0)
			params["oauth_token"]=_accessTokenKey;
		if (_pin && _pin.length > 0)
			params["oauth_verifier"]=_pin;
		params["oauth_signature_method"]="HMAC-SHA1";
		params["oauth_timestamp"]=now.time.toString().substr(0, 10);
		params["oauth_nonce"]=GUID.createGUID();
		params["oauth_version"]="1.0";
		params["oauth_callback"]="oob";

		var retParams:Array=[];
		for (var param:String in params)
		{
			if (params[param] != null)
				retParams.push(param + "=" + StringEncoders.urlEncodeUtf8String(params[param].toString()));
		}
		retParams.sort();
		var paramsStr:String=retParams.join("&");

		var msgStr:String=StringEncoders.urlEncodeUtf8String(URLRequestMethod.POST.toUpperCase()) + "&";
		msgStr+=StringEncoders.urlEncodeUtf8String(Statics.OAUTH_ACCESS_TOKEN_REQUEST_URL);
		msgStr+="&";
		msgStr+=StringEncoders.urlEncodeUtf8String(paramsStr);
		var secrectStr:String=_consumerSecret + "&";
		secrectStr+=_accessTokenSecret;
		var sig:String=Base64.encode(HMAC.hash(secrectStr, msgStr, SHA1));
		params["oauth_signature"]=sig;
		req.data=params;
		oauthLoader.load(req);//请求access, oauthLoader_onComplete
	}
	
	//未登陆亦可执行到此
}




/**
 *	验证证书 成功，返回微博信息
 * @param event
 *
 */
private function onVerifyCredentialResult(event:MicroBlogEvent):void
{
	//trace("onVerifyCredentialResult:"+_mb.currentResult);

	styles();
	addMainPage();
	addListeners();

	addMainMicroBlogs();
}

/**
 * 验证证书 失败
 *
 */
private function verifyCredentialsError(event:MicroBlogErrorEvent):void
{
	trace("verifyCredentialsError : " + event.message);
}



/*--------------------------------------------------------------------------------------------------------*/

private function styles():void
{
	/*
	//窗口位置，亦可设置宽高
	var window:NativeWindow=stage.nativeWindow;
	var windowsize:Rectangle=new Rectangle(0,0);
	window.bounds=windowsize;
	*/
	
	/*
	//窗口初始位置
	var screenWidth:int;
	var screenHeight:int;
	for each (var screen:Screen in Screen.screens)
	{
		//_txt.text = screen.bounds.width + "x" + screen.bounds.height + "Color depth:" + screen.colorDepth + "bit";
		screenWidth=screen.bounds.width;
		screenHeight=screen.bounds.height;
	}
	this.nativeWindow.x=screenWidth * 0.6;
	this.nativeWindow.y=(screenHeight - this.nativeWindow.height) / 2;
	*/
	
	
	this.width=Statics.appWidth;
	this.height=Statics.appHeight;

	mainPanel.visible=true;
	mainPanel.title=Statics.appName;

	//this.showStatusBar = false; //不显示底部状态栏
}

private function addObjects():void
{

}

private function addMainPage():void
{
	userProfile=new UserProfile();
	profileXML=new XML(_mb.currentResult);
	
	userProfile.friendsBtn.addEventListener(MouseEvent.CLICK, friendsBtnHandler);
	userProfile.myWeibo.addEventListener(MouseEvent.CLICK, myWeiboHandler);

	userProfile.avatar.source=profileXML.profile_image_url; //头像
	userProfile.screen_name.text=profileXML.screen_name; //昵称
	userProfile.location.text=profileXML.location; //所在地
	userProfile.count.text="关注:" + profileXML.friends_count + " 粉丝:" + profileXML.followers_count + " 微博:" + profileXML.statuses_count;

	topContainer.addElement(userProfile);
	
	//player
	var player:Play = new Play();
	playerContaier.addElement(player);
}

private function addListeners():void
{
	//this.addEventListener(MouseEvent.MOUSE_DOWN, dragHandler);
	topContainer.addEventListener(MouseEvent.MOUSE_DOWN, dragHandler);
	
	write.addEventListener(MouseEvent.CLICK, writeHandler);
	refresh.addEventListener(MouseEvent.CLICK, refreshHandler);
	closeBtn.addEventListener(MouseEvent.CLICK, closeBtnHandler);

}


/**
 *	窗口拖拽
 * @param event
 *
 */
private function dragHandler(event:MouseEvent):void
{
	this.stage.nativeWindow.startMove();
}


/**
 *	加载主页微博
 *
 */
private function addMainMicroBlogs():void
{
	//用户信息
	_mb.addEventListener(MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT, addMainMicroBlogsResult);
	_mb.addEventListener(MicroBlogErrorEvent.LOAD_FRIENDS_TIMELINE_ERROR, addMainMicroBlogsError);

	//主微博回复转发数
	_mb.addEventListener(MicroBlogEvent.LOAD_STATUS_COUNTS_RESULT, countsResult);
	_mb.addEventListener(MicroBlogErrorEvent.LOAD_STATUS_COUNTS_ERROR, countsError);
	
	/*
	_mb.addEventListener(MicroBlogEvent.LOAD_STATUS_INFO_RESULT, infoResult);
	_mb.addEventListener(MicroBlogErrorEvent.LOAD_STATUS_INFO_ERROR, infoError);
	*/
	
	//发微博
	_mb.addEventListener(MicroBlogEvent.UPDATE_STATUS_RESULT, updateStatusResultHandler);
	_mb.addEventListener(MicroBlogErrorEvent.UPDATE_STATUS_ERROR, updateStatusErrorHandler);
	
	//请求关注列表
	_mb.addEventListener(MicroBlogEvent.LOAD_FRIENDS_INFO_RESULT, friendsResultHandler);
	_mb.addEventListener(MicroBlogErrorEvent.LOAD_FRIENDS_INFO_ERROR, friendsErrorHandler);

	_mb.loadFriendsTimeline();//MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT

}

/**
 * 加载主页微博成功
 * @param event
 *
 */
private function addMainMicroBlogsResult(event:MicroBlogEvent):void
{
	Container.cleanContainer(listContainer);

	var tempArr:Array = [];//主微博
	var len:int=event.result.length;
	for (var i:int=0; i < len; i++)
	{
		//trace(event.result[i]);//[object MicroBlogStatus]

		var mainList:MainList=new MainList();

		//本条
		mainList.avatar.source=event.result[i].user.profileImageUrl; //头像
		mainList.screen_name.text=event.result[i].user.screenName; //昵称
		mainList.contentText.text=event.result[i].text; //微博内容

		var timeTemp:String=event.result[i].createdAt.fullYear;
		timeTemp+="-";
		timeTemp+=(event.result[i].createdAt.month + 1).toString();
		timeTemp+="-";
		timeTemp+=event.result[i].createdAt.date;
		timeTemp+=" ";
		timeTemp+=event.result[i].createdAt.hours < 10 ? "0" + event.result[i].createdAt.hours : event.result[i].createdAt.hours;
		timeTemp+=":";
		timeTemp+=event.result[i].createdAt.minutes < 10 ? "0" + event.result[i].createdAt.minutes : event.result[i].createdAt.minutes;
		mainList.otherText.textFlow=TextConverter.importToFlow(timeTemp + "   " + event.result[i].source, TextConverter.TEXT_FIELD_HTML_FORMAT); //时间、来源、转发数、回复数

		if (event.result[i].thumbPicUrl != "")
		{
			mainList.thumbPic.addEventListener(MouseEvent.CLICK, thumbPicHandler);
			mainList.thumbPic.source=event.result[i].thumbPicUrl; //缩略图
		}
		
		tempArr.push(event.result[i].id);//微博id

		//原微博
		if (event.result[i].repost != null)
		{
			var retweeted:Retweeted=new Retweeted();
			mainList.retweetedContainer.addElement(retweeted);
			retweeted.retweeted_screen_name.text="@" + event.result[i].repost.user.screenName+":"; //昵称
			retweeted.retweeted_contentText.text=event.result[i].repost.text; //微博内容
			retweeted.retweeted_thumbPic.source=event.result[i].repost.thumbPicUrl; //缩略图
			
			rtCounterArr.push(event.result[i].repost.id);
			retweetedArr.push(retweeted);
		}

		listContainer.addElement(mainList);
	}
	_mb.loadStatusCounts(tempArr);//请求评论转发数
}

/**
 * 加载主页微博失败
 * @param event
 *
 */
private function addMainMicroBlogsError(event:MicroBlogErrorEvent):void
{
	trace("主页微博加载失败");
}

/**
 *	回复转发数 
 * @param event
 * 
 */
private function countsResult(event:MicroBlogEvent):void
{
	if(rtCounterNum == 0)
	{
		//原微博
		for (var i:int=0; i < event.result.length; i++)
		{
			//转发评论数，时准时不准!?
			(listContainer.getElementAt(i) as MainList).otherText.text += "   转:"+event.result[i].repostsCount+" 评:"+event.result[i].commentsCount;
		}
		
		rtCounterNum = 1;
		_mb.loadStatusCounts(rtCounterArr);//请求引用微博的评论转发数
	}
	else
	{
		//引用微博
		for(var j:int=0;j<event.result.length;j++)
		{
			retweetedArr[j].retweeted_count.text = "转:"+event.result[j].repostsCount+" 评:"+event.result[j].commentsCount;
		}
		rtCounterNum = 0;
	}
}
/**
 *	回复转发数 失败 
 * @param event
 * 
 */
private function countsError(event:MicroBlogErrorEvent):void
{
	trace("countsError");
}



private function infoResult(event:MicroBlogEvent):void
{
	trace("infoResult : "+event.result.id);
}
private function infoError(evnet:MicroBlogErrorEvent):void
{
	trace("infoError");
}






/**
 *	点击缩略图
 * @param event
 *
 */
private function thumbPicHandler(event:MouseEvent):void
{
	trace("点击缩略图");
}

/**
 *	主界面发微博按钮 
 * @param event
 * 
 */
private function writeHandler(event:MouseEvent):void
{
	write.mouseEnabled = false;
	
	//主程序调用，并关闭父窗口
	writeComponent = new Write();
	writeComponent.advOpen(this);
	writeComponent.move(this.nativeWindow.x+this.width+3, this.nativeWindow.y);
	writeComponent.updateStatusBtn.addEventListener(MouseEvent.CLICK, updateStatusHandler);
	writeComponent.cancelBtn.addEventListener(MouseEvent.CLICK, cancelBtnHandler);
	/*
	if(w.parentWindow.hasOwnProperty("close"))
	{
		w.parentWindow.close(); //调用父窗口的close方法
	}
	*/
}


/**
 *	小框发微博按钮 
 * @param event
 * 
 */
private function updateStatusHandler(event:MouseEvent):void
{
	if(writeComponent.ta.text != "" && writeComponent.ta.text != null)
	{
		writeComponent.ta.enabled = false;
		writeComponent.updateStatusBtn.mouseEnabled = false;
		writeComponent.writePanel.title += " - 发布中。。。";
		
		_mb.updateStatus(writeComponent.ta.text);
	}
	else
	{
		Alert.show("不能发空消息", "错误");
	}
}

/**
 *	小框取消按钮 
 * @param event
 * 
 */
private function cancelBtnHandler(event:MouseEvent):void
{
	writeComponent.close();
	write.mouseEnabled = true;
}

/**
 *	发微博成功  _mb.updateStatus
 * @param event
 * 
 */
private function updateStatusResultHandler(event:MicroBlogEvent):void
{
	trace(event.result);
	writeComponent.close();
	write.mouseEnabled = true;
}
/**
 *	发微博失败  _mb.updateStatus
 * @param event
 * 
 */
private function updateStatusErrorHandler(event:MicroBlogErrorEvent):void
{
	trace(event.message);
	writeComponent.close();
	write.mouseEnabled = true;
}

/**
 *	主界面刷新按钮 
 * @param event
 * 
 */
private function refreshHandler(event:MouseEvent):void
{
	_mb.loadFriendsTimeline();
}
/**
 *	关闭 
 * @param event
 * 
 */
private function closeBtnHandler(event:MouseEvent):void
{
	this.exit();
}
/**
 *	我的微薄，刷新主界面 
 * @param event
 * 
 */
private function myWeiboHandler(event:MouseEvent):void
{
	_mb.loadFriendsTimeline();
}

/**
 *	点击关注按钮 
 * @param event
 * 
 */
private function friendsBtnHandler(event:MouseEvent):void
{
	_mb.loadFriendsInfo();
}
/**
 *	获取关注列表成功 
 * @param event
 * 
 */
private function friendsResultHandler(event:MicroBlogEvent):void
{
	Container.cleanContainer(listContainer);
	
	var len:int = event.result.length;
	for(var i:int = 0; i<len; i++)
	{
		var _userProfile:UserProfile = new UserProfile();

		_userProfile.avatar.source=event.result[i].profileImageUrl; //头像
		_userProfile.screen_name.text=event.result[i].screenName; //昵称
		_userProfile.location.text=event.result[i].location; //所在地
		_userProfile.count.text="关注:" + event.result[i].friendsCount + " 粉丝:" + event.result[i].followersCount + " 微博:" + event.result[i].statusesCount;
		_userProfile.y = i*100 + 4;
		_userProfile.profileBtns.visible = false;
		listContainer.addElement(_userProfile);
	}
}
/**
 *	获取关注列表失败 
 * @param evnet
 * 
 */
private function friendsErrorHandler(evnet:MicroBlogErrorEvent):void
{
	trace("friendsErrorHandler");
}


